package platform.user.auth.token;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import platform.user.auth.UserDetails;
import platform.user.auth.token.store.TokenStore;
import platform.user.model.User;

/**
 * Token 认证器
 *
 * @author roamer
 * @version V1.0
 * @date 2019-03-10 15:15
 */
@Component
public class TokenAuthenticator {

    @Autowired
    private TokenStore tokenStore;

    public void authenticateToken(String tokenValue, String mangerTokenValue) {
        SessionToken token = null;
        SessionToken managerToken = null;
        try {
            if (tokenValue == null) {
                throw new AuthenticationCredentialsNotFoundException("Token not found");
            }
            if (tokenStore.isValidToken(tokenValue)) {
                // 获取安全上下文环境
                SecurityContext context = SecurityContextHolder.getContext();
                UserDetails userDetails = new UserDetails(new User());

                UserDetails managerDetails = null;
                TokenAuthenticationToken authentication = new TokenAuthenticationToken(userDetails, token,
                                                                                       managerDetails);

                // Authenticated
                authentication.setAuthenticated(true);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } else {
                throw new BadCredentialsException("Bad Credentials");
            }
        } catch (AuthenticationException e) {
            SecurityContextHolder.clearContext();
        }
    }
}
